package com.efounder.chat.activity;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.core.xml.StubObject;
import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.OpenEthRequest;
import com.efounder.chat.struct.MessageChildTypeConstant;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.IdentifyQrCodeManager;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.chat.utils.PansoftCloudUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.FileUtils;
import com.utilcode.util.TimeUtils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;



/**
 * 别的收款码
 */
public class OtherUserMoneyCodeActivity extends BaseActivity implements View.OnClickListener {


    private TextView tvTitle;
    private User otherUser;
    private String payMode;
    private AlertDialog alertDialog;
    private IdentifyQrCodeManager identifyQrCodeManager;
    private ImageView ivCode;
    private TextView tvScan;
    private TextView tvSaveCode;
    private String url;
    private String chatToUserId;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wechatview_activity_other_money_code);
        initView();
        initData();

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        identifyQrCodeManager.realease();
    }


    private void initView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        ivCode = (ImageView) findViewById(R.id.iv_code);
        tvScan = (TextView) findViewById(R.id.tv_scan);
        tvSaveCode = (TextView) findViewById(R.id.tv_save_code);
        tvScan.setOnClickListener(this);
        tvSaveCode.setOnClickListener(this);

    }

    private void initData() {

        identifyQrCodeManager = new IdentifyQrCodeManager();
        StubObject stubObject = (StubObject) getIntent().getSerializableExtra("stubObject");
        if (stubObject == null) {
            return;
        }
        chatToUserId = stubObject.getString("toUserId", "");
        //weixin  zhifubao
        payMode = stubObject.getString("payMode", "");

        otherUser = WeChatDBManager.getInstance().getOneFriendById(Integer.valueOf(chatToUserId));
        String noteName = "";
        if (otherUser.isExist()) {
            noteName = otherUser.getReMark();
        } else {
            otherUser = WeChatDBManager.getInstance().getOneUserById(Integer.valueOf(chatToUserId));
            noteName = otherUser.getNickName();
        }
        String titleString = noteName + (payMode.equals("weixin") ? ResStringUtil.getString(R.string.wrchatview_de_wx) : ResStringUtil.getString(R.string.wrchatview_de_zfb)) + ResStringUtil.getString(R.string.wrchatview_collection_code);
        tvTitle.setText(titleString);
        requestData();

    }

    private void requestData() {
        OpenEthRequest.getUserEthByImUserId(this, otherUser.getId(), new OpenEthRequest.EthUserRequestListener() {
            @Override
            public void onSuccess(User user) {
                if ("weixin".equals(payMode)) {
                    url = user.getWeixinQrUrl();

                } else {
                    url = user.getZhifubaoQrUrl();
                }
                showImage(url);
            }

            @Override
            public void onSuccess(String ethAddress, String publicKey, String RSAPublicKey) {

            }

            @Override
            public void onFail(String error) {
                ToastUtil.showToast(OtherUserMoneyCodeActivity.this, ResStringUtil.getString(R.string.chat_get_info_fail));
            }
        });


        //  showAlert();
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_scan) {
            saveOrScanQrCode(true, url);
        } else if (id == R.id.tv_save_code) {
            saveOrScanQrCode(false, url);

        }
    }


    private void showAlert() {
        if (alertDialog != null && alertDialog.isShowing()) {
            alertDialog.dismiss();
        }
        alertDialog = new AlertDialog.Builder(this)
                .setTitle(R.string.common_text_hint)
                .setCancelable(false)
                .setMessage(ResStringUtil.getString(R.string.wrchatview_not_set_code))
                .setNegativeButton(R.string.common_text_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                })
                .setPositiveButton(ResStringUtil.getString(R.string.wrchatview_remind_him), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        sendToFriend();
                    }
                })
//                .setPositiveButton("提醒他", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                })
                .create();
        alertDialog.show();

    }

    /**
     * 发送给好友，提醒设置二维码
     */
    private void sendToFriend() {
        Map<String, Object> map = new HashMap<>();
        String imgUrl = "https://panserver.solarsource.cn/panserver/files/ca324340-0409-4c82-8b22-2cb0a911f742/download";
        map.put("title", ResStringUtil.getString(R.string.wrchatview_collection_code_remind));
        map.put("image", imgUrl);
        map.put("smallIcon", imgUrl);
        map.put("time", TimeUtils.getNowString());
        map.put("content", ResStringUtil.getString(R.string.wrchatview_remind_you_set));
        map.put("systemName", ResStringUtil.getString(R.string.wrchatview_collection_code_remind));
        map.put("AndroidShow", "com.efounder.chat.activity.SetMyReceiveMoneyCodeActivity");
        map.put("show", "JFPaymenCodePageController");
        map.put("viewType", "display");
        net.sf.json.JSONObject jsonObject1 = net.sf.json.JSONObject.fromObject(map);
        IMStruct002 imStruct002 = new IMStruct002();
        try {
            imStruct002.setBody(jsonObject1.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        long currenttime = System.currentTimeMillis();
        imStruct002.setTime(currenttime);
        imStruct002.setFromUserId(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
        imStruct002.setMessageChildType(MessageChildTypeConstant.subtype_common);
        imStruct002.setToUserType(StructFactory.TO_USER_TYPE_PERSONAL);
        imStruct002.setToUserId(Integer.valueOf(chatToUserId));
        JFMessageManager.getInstance().sendMessage(imStruct002);
        finish();
    }
    /**
     * 显示图片
     *
     * @param url
     */
    private void showImage(String url) {
        if (url == null || "".equals(url)) {
            showAlert();
            return;
        }

        LoadingDataUtilBlack.show(this);
        Glide.with(this)
                .load(url)
                .apply(new RequestOptions()
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        //.transform(new RoundedCorners(10))
                        .transform(new RoundedCornersTransformation(20, 0,
                                RoundedCornersTransformation.CornerType.ALL))
                )

                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        LoadingDataUtilBlack.dismiss();
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        LoadingDataUtilBlack.dismiss();
                        return false;
                    }
                })
                .into(ivCode);
    }

    /**
     * 保存或者识别二维码
     *
     * @param isScan
     * @param url
     */
    private void saveOrScanQrCode(final boolean isScan, final String url) {
        Glide.with(this).asFile().load(url).into(new SimpleTarget<File>() {
            @Override
            public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) {

                File picPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                if (!picPath.exists()) {
                    picPath.mkdirs();
                }
                String fileName = PansoftCloudUtil.getPansoftCloudFileId(url) + ".png";
                final File file = new File(picPath.getAbsolutePath(), fileName);


                if (!isScan) {
                    FileUtils.copyFile(resource, file,
                            new FileUtils.OnReplaceListener() {
                                @Override
                                public boolean onReplace() {
                                    //存在同名文件是否替换
                                    //弹出提示，已保存
                                    //华为某些机型连续保存会存在删除覆盖问题
                                    ToastUtil.showToast(OtherUserMoneyCodeActivity.this, ResStringUtil.getString(R.string.wrchatview_save_suc) + file.getAbsolutePath());
                                    return false;
                                }
                            });

                    if (ImageUtil.isGifFile(file)) {
                        String newPath = file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("."));
                        File gifFile = new File(newPath + ".gif");
                        file.renameTo(gifFile);
                        // 通知图库更新（注意这里传的是gifFile）
                        ImageUtil.galleryAddPic(gifFile.getAbsolutePath());
                    } else {
                        // 通知图库更新
                        ImageUtil.galleryAddPic(file.getAbsolutePath());
                    }

                    ToastUtil.showToast(OtherUserMoneyCodeActivity.this, ResStringUtil.getString(R.string.wrchatview_save_suc) + file.getAbsolutePath());

                } else {
                    LoadingDataUtilBlack.show(OtherUserMoneyCodeActivity.this, ResStringUtil.getString(R.string.wrchatview_identification));
                    identifyQrCodeManager.scanImage(resource.getAbsolutePath(), new IdentifyQrCodeManager.ScanCallBack() {
                        @Override
                        public void scanSuccess(String filePath,final String reult) {
                            LoadingDataUtilBlack.dismiss();
                            alertDialog = new AlertDialog.Builder(OtherUserMoneyCodeActivity.this)
                                    .setTitle(ResStringUtil.getString(R.string.wrchatview_recognition_result))
                                    .setMessage(reult)
                                    .setPositiveButton(ResStringUtil.getString(R.string.wrchatview_copy), new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();

                                            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                                            // 将文本内容放到系统剪贴板里。
                                            cm.setText(reult);
                                            ToastUtil.showToast(getApplicationContext(), ResStringUtil.getString(R.string.chat_copy_to_clipboard));
                                        }
                                    })
                                    .setNegativeButton(R.string.common_text_cancel, null)
                                    .create();
                            alertDialog.show();

                            // ToastUtil.showToast(OtherUserMoneyCodeActivity.this, reult);

                        }

                        @Override
                        public void scanFail() {
                            LoadingDataUtilBlack.dismiss();
                            ToastUtil.showToast(OtherUserMoneyCodeActivity.this, ResStringUtil.getString(R.string.wrchatview_identify_fail));
                        }
                    });
                }


            }
        });
    }
}
